import logging
from datetime import date, timedelta
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from django.http import HttpResponseServerError

from users.models import User
from goods.models import GoodsVisitCount
from meiduo_admin.serializers.statistical import GoodsDaySerializer

logger = logging.getLogger('django')


class UserCountView(APIView):
    """
    用户总量统计
    """
    permission_classes = [IsAdminUser]  # 指定超级管理员用户才能访问该视图

    def get(self, request):
        # 获取数据库中的用户总量
        try:
            count = User.objects.all().count()
        except Exception as e:
            logger.error(e)
            return HttpResponseServerError('读取数据库失败')

        # 获取当天日期
        today_date = date.today()

        # 构造响应结果
        content = {
            'count': count,
            'date': today_date
        }

        # 返回数据
        return Response(content)


class UserDayActiveCountView(APIView):
    """
    统计日活用户量
    """
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当天时间
        today_date = date.today()

        # 通过时间查询最后一次登录在当天的用户量
        try:
            count = User.objects.filter(last_login__gte=today_date).count()
        except Exception as e:
            logger.error(e)
            return HttpResponseServerError('查询数据库失败')

        # 构造响应结果
        # 返回数据
        return Response({'count': count, 'date': today_date})


class DayOrderUserView(APIView):
    """
    统计日下单用户量
    """
    pass


class UserMonthIncrementView(APIView):
    """
    统计月增用户量
    """
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前时间日期
        end_date = date.today()

        # 获取当前时间逆推29天的日期
        start_date = end_date - timedelta(29)
        cur_date = start_date
        next_date = cur_date + timedelta(1)

        # 统计这３０天里每天的用户增加量
        day_increment_list = list()
        for i in range(30):
            try:
                count = User.objects.filter(date_joined__gte=cur_date, date_joined__lt=next_date).count()
                day_increment_list.append({'count': count, 'date': cur_date})
                cur_date = next_date
                next_date += timedelta(1)
            except Exception as e:
                logger.error(e)
                return HttpResponseServerError('查询数据库失败')

        return Response(day_increment_list)


class GoodsDayView(APIView):
    """
    分类商品每日的访问量统计
    """
    permission_classes = [IsAdminUser]

    # 方法一
    # def get(self, request):
    #     # 获取当天日期
    #     today_date = date.today()
    #
    #     # 按当前日期过滤率商品信息
    #     categories = GoodsVisitCount.objects.filter(date__gte=today_date)
    #
    #     # 返回结果
    #     content = [{'category': cat.category.name, 'count': cat.count} for cat in categories]
    #     return Response(content)

    # 方法二：使用序列化器
    def get(self, request):
        today_date = date.today()
        categories = GoodsVisitCount.objects.filter(date=today_date)
        ser = GoodsDaySerializer(categories, many=True)

        return Response(ser.data)

